//
//  ClusterAnnotationView.m
//  officialDemo2D
//
//  Created by yi chen on 14-5-15.
//  Copyright (c) 2014年 AutoNavi. All rights reserved.
//

#import "ClusterAnnotationView.h"
#import "TraceModel.h"

static CGFloat const ScaleFactorAlpha = 0.3;
static CGFloat const ScaleFactorBeta = 0.4;
const NSInteger kMaxWidth = 414;

#define kCalloutWidth       kScreenWidth * 0.9
#define kCalloutHeight      70.0


/* 返回rect的中心. */
CGPoint RectCenter(CGRect rect)
{
    return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}

/* 返回中心为center，尺寸为rect.size的rect. */
CGRect CenterRect(CGRect rect, CGPoint center)
{
    CGRect r = CGRectMake(center.x - rect.size.width/2.0,
                          center.y - rect.size.height/2.0,
                          rect.size.width,
                          rect.size.height);
    return r;
}

/* 根据count计算annotation的scale. */
CGFloat ScaledValueForValue(CGFloat value)
{
    return 1.0 / (1.0 + expf(-1 * ScaleFactorAlpha * powf(value, ScaleFactorBeta)));
}

#pragma mark -

@interface ClusterAnnotationView ()

@property (nonatomic, strong) UILabel *countLabel;

@property (nonatomic, strong) UILabel *nameLabel;

@property (nonatomic) UIColor *innerCircleStrokeColor;
@property (nonatomic) UIColor *innerCircleFillColor;
@property (nonatomic) UIColor *outerCircleStrokeColor;

@end

@implementation ClusterAnnotationView

#pragma mark Initialization

- (id)initWithAnnotation:(id<MAAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if (self) {
        //self.bounds = CGRectMake(0, 0, 25, 25);
        self.backgroundColor = [UIColor clearColor];
        self.image = IMAGE_NAMED(@"online_location");// 相当于初始化一个Frame，否则frame获取不到,nameLabel会偏移
        [self setupLabel];
        [self setCount:1];
        
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
    if (self.selected == selected) {
        return;
    }
    // 只允许单台设备弹出
    if (_count != 1) return;
    
    if (selected) {
        if (self.calloutView == nil) {
            //self.calloutView = [[CustomCalloutView alloc] init];
            self.calloutView = [[CustomCalloutView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth * 0.90, 0)];
            self.calloutView.center = CGPointMake(CGRectGetWidth(self.bounds) / 2.f,
            0);
        }
        [self addSubview:self.calloutView];
        
        self.calloutView.sd_layout
        .centerXEqualToView(self)
        .bottomSpaceToView(self, 27)
        .widthIs(kScreenWidth * 0.9);
        
        CLLocationCoordinate2D coorinate = [self.annotation coordinate];
        for (EquipmentModel *eModel in _dataSource) {
            if ([eModel.pointModel.lat doubleValue] == coorinate.latitude && [eModel.pointModel.lng doubleValue] == coorinate.longitude){
                [self.calloutView setModel:eModel];
            }
        }
        
    } else {
        [self.calloutView removeFromSuperview];
    }
    [super setSelected:selected animated:animated];
}

- (void)setTraceModel:(TraceModel *)traceModel
{
    _traceModel = traceModel;
    // 刷新弹窗信息
    [self.calloutView setTModel:traceModel];

    // 更新设备方向
    self.imageView.transform = CGAffineTransformMakeRotation([traceModel.dir floatValue] / 180.0*M_PI);
}


// 设置图标和车主名字
- (void)setDataSource:(NSMutableArray *)dataSource
{
    _dataSource = dataSource;
    
    CLLocationCoordinate2D coorinate = [self.annotation coordinate];
    
    for (EquipmentModel *eModel in dataSource)
    {
        if ([eModel.pointModel.lat doubleValue] == coorinate.latitude && [eModel.pointModel.lng doubleValue] == coorinate.longitude)
        {
            if (eModel.ownerName.length) {
                self.nameLabel.text = eModel.ownerName;
            } else {
                NSString *name = NSStringFormat(@"%@-%@",eModel.eqModel,[eModel.eqNo substringFromIndex:10]);
                self.nameLabel.text = name;
            }
            
            // 设备方向
            if (![eModel.pointModel.dir isKindOfClass:[NSNull class]]) {
                self.imageView.transform = CGAffineTransformMakeRotation((CGFloat)([eModel.pointModel.dir doubleValue] / 180.0*M_PI));
            } else {
                self.imageView.transform = CGAffineTransformMakeRotation(0);
            }
            
            // 2是离线
            if (![eModel.status isEqualToString:@"2"]) {
                self.image = IMAGE_NAMED(@"online_location");
            } else {
                self.image = IMAGE_NAMED(@"offline_location");
            }
        }
    }
}

#pragma mark Utility

- (void)setupLabel
{
    // 数量
    _countLabel = [[UILabel alloc] initWithFrame:self.frame];
    _countLabel.backgroundColor = [UIColor clearColor];
    _countLabel.textColor       = [UIColor whiteColor];
    _countLabel.textAlignment   = NSTextAlignmentCenter;
    _countLabel.adjustsFontSizeToFitWidth = YES;
    _countLabel.numberOfLines = 1;
    _countLabel.font = [UIFont boldSystemFontOfSize:12];
    _countLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    [self addSubview:_countLabel];
    
    // 车主姓名
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    _nameLabel.center = CGPointMake(CGRectGetWidth(self.bounds) / 2.f ,CGRectGetMaxY(self.bounds) + 7);
    _nameLabel.backgroundColor = [UIColor clearColor];
    
    if (@available(iOS 13.0, *)) {
        UIColor *nameColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kTextBlackColor;
            } else {
                return kDarkTextColor;
            }
        }];
        _nameLabel.textColor = nameColor;
        
        _countLabel.textColor = kDarkTextColor;
    } else {
        _nameLabel.textColor = kTextBlackColor;
    }
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.numberOfLines = 1;
    _nameLabel.font = [UIFont systemFontOfSize:9];
    [self addSubview:_nameLabel];
    
//    [_nameLabel setSingleLineAutoResizeWithMaxWidth:100];
//    _nameLabel.sd_layout
//    .centerXEqualToView(self)
//    .topSpaceToView(self, 21)
//    .autoWidthRatio(0)
//    .heightIs(20);
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    NSArray *subViews = self.subviews;
    if ([subViews count] > 1) {
        for (UIView *aSubView in subViews) {
            if ([aSubView pointInside:[self convertPoint:point toView:aSubView] withEvent:event]) {
                return YES;
            }
        }
    }
    if (point.x > 0 && point.x < self.frame.size.width && point.y > 0 && point.y < self.frame.size.height) {
        return YES;
    }
    return NO;
}

- (void)setCount:(NSUInteger)count
{
    _count = count;
    PPLog(@"count == %ld",count);
    /* 按count数目设置view的大小. */
    CGRect newBounds = CGRectMake(0, 0, roundf(44 * ScaledValueForValue(count)), roundf(44 * ScaledValueForValue(count)));
    self.frame = CenterRect(newBounds, self.center);
    
    CGRect newLabelBounds = CGRectMake(0, 0, newBounds.size.width / 1.3, newBounds.size.height / 1.3);
    self.countLabel.frame = CenterRect(newLabelBounds, RectCenter(newBounds));
    self.countLabel.text = [@(_count) stringValue];
    
    [self setNeedsDisplay];
    
    if (_count == 1) {
        self.countLabel.hidden = YES;
        self.imageView.hidden = NO;
        self.nameLabel.hidden = NO;
    } else {
        self.countLabel.hidden = NO;
        self.imageView.hidden = YES;
        self.nameLabel.hidden = YES;
    }
}

#pragma mark - annimation

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    [self addBounceAnnimation];
}

- (void)addBounceAnnimation
{
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    
    bounceAnimation.values = @[@(0.05), @(1.1), @(0.9), @(1)];
    bounceAnimation.duration = 0.6;
    
    NSMutableArray *timingFunctions = [[NSMutableArray alloc] initWithCapacity:bounceAnimation.values.count];
    for (NSUInteger i = 0; i < bounceAnimation.values.count; i++) {
        [timingFunctions addObject:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    }
    [bounceAnimation setTimingFunctions:timingFunctions.copy];
    
    bounceAnimation.removedOnCompletion = NO;
    
    [self.layer addAnimation:bounceAnimation forKey:@"bounce"];
}

#pragma mark draw rect

- (void)drawRect:(CGRect)rect
{
    if (@available(iOS 13.0, *)) {
        UIColor *innerCircleStrokeColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return UIColor.whiteColor;
            } else {
                return kRgb(203, 203, 203);
            }
        }];
        _innerCircleStrokeColor = innerCircleStrokeColor;
        
        UIColor *innerCircleFillColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return UIColor.redColor;
            } else {
                return kRgb(220, 0, 0);
            }
        }];
        _innerCircleFillColor = innerCircleFillColor;
        
        UIColor *outerCircleStrokeColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return [UIColor colorWithWhite:0 alpha:0.25];
            } else {
                return UIColor.clearColor;
            }
        }];
        _outerCircleStrokeColor = outerCircleStrokeColor;
    } else {
        _innerCircleStrokeColor = UIColor.whiteColor;
        _innerCircleFillColor = UIColor.redColor;
        _outerCircleStrokeColor = [UIColor colorWithWhite:0 alpha:0.25];
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(context, true);
    
    UIColor *outerCircleStrokeColor = _outerCircleStrokeColor;

    UIColor *innerCircleStrokeColor = _innerCircleStrokeColor;
    UIColor *innerCircleFillColor = _innerCircleFillColor;

    CGRect circleFrame = CGRectInset(rect, 4, 4);

    [outerCircleStrokeColor setStroke];
    CGContextSetLineWidth(context, 5.0);
    CGContextStrokeEllipseInRect(context, circleFrame);

    [innerCircleStrokeColor setStroke];
    CGContextSetLineWidth(context, 4);
    CGContextStrokeEllipseInRect(context, circleFrame);

    [innerCircleFillColor setFill];
    CGContextFillEllipseInRect(context, circleFrame);
}

@end
